package com.joker.demo.admin.router.impl;

import com.joker.demo.admin.router.ExecutorRouter;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 最不经常使用（LFU）路由策略
 * @author : feixiang.li
 * @since : 2025-07-29 17:30
 */
public class LeastFrequentlyUsedExecutorRouter implements ExecutorRouter {
    
    // 记录每个地址的使用次数
    private static final Map<String, AtomicInteger> usageCount = new ConcurrentHashMap<>();
    
    @Override
    public String route(String jobId, List<String> addressList) {
        if (addressList == null || addressList.isEmpty()) {
            return null;
        }
        
        // 初始化未记录的地址
        for (String address : addressList) {
            usageCount.putIfAbsent(address, new AtomicInteger(0));
        }
        
        // 找到使用次数最少的地址
        String leastUsedAddress = null;
        int minCount = Integer.MAX_VALUE;
        
        for (String address : addressList) {
            AtomicInteger count = usageCount.get(address);
            if (count != null && count.get() < minCount) {
                minCount = count.get();
                leastUsedAddress = address;
            }
        }
        
        // 增加选中地址的使用次数
        if (leastUsedAddress != null) {
            usageCount.get(leastUsedAddress).incrementAndGet();
        }
        
        return leastUsedAddress;
    }
} 